import { defineConfig, loadEnv, type ConfigEnv, type UserConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import ElementPlus from 'unplugin-element-plus/vite'
import viteImagemin from 'vite-plugin-imagemin'
import { visualizer } from 'rollup-plugin-visualizer'
import Unocss from 'unocss/vite'

// https://vite.dev/config/
export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  const env = loadEnv(mode, process.cwd())
  const prot = env.VITE_BASE_PORT ? parseInt(env.VITE_BASE_PORT) : 9527

  return {
    base: env.VITE_BASE_PATH,
    server: {
      hmr: true,
      host: '0.0.0.0',
      port: prot, // 服务器端口号
      proxy: {
        '/api': {
          target: env.VITE_API_URL,
          ws: true,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ' ')
        }
      }
    },
    build: {
      outDir: 'dist',
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name]-[hash].js', // 引入文件名的名称
          entryFileNames: 'js/[name]-[hash].js', // 包的入口文件名称
          assetFileNames: (assetInfo) => {
            const names = assetInfo.names
            for (let i = 0; i < names.length; i++) {
              if (
                assetInfo.type === 'asset' &&
                /\.(jpe?g|png|gif|svg)$/i.test(names[i] ?? '')
              ) {
                return 'static/img/[name].[hash][ext]'
              }
              if (
                assetInfo.type === 'asset' &&
                /\.(ttf|woff|woff2|eot)$/i.test(names[i] ?? '')
              ) {
                return 'static/fonts/[name].[hash][ext]'
              }
            }
            return 'static/[ext]/[name]-[hash].[ext]'
          },
          manualChunks: (id) => {
            if (id.includes('node_modules')) {
              if (id.includes('vue')) return 'chunk-vue'
              if (id.includes('vue-router')) return 'chunk-vueRouter'
              if (id.includes('pinia')) return 'chunk-pinia'
              if (id.includes('element-plus')) return 'chunk-elementPlus'
              if (id.includes('lodash')) return 'chunk-lodash'
              return 'chunk-vendors'
            }
            if (id.includes('src/components')) return 'chunk-commons'
          },
          hoistTransitiveImports: false // 防止变量提升问题
        }
      }
    },
    resolve: {
      alias: [
        {
          find: '@',
          replacement: path.resolve(__dirname, 'src')
        }
      ]
    },
    plugins: [
      vue(),
      Unocss(),
      AutoImport({
        // api
        resolvers: [ElementPlusResolver()],
        imports: ['vue', 'vue-router', 'pinia'],
        eslintrc: { enabled: false } // 给 eslint 生成的配置，只需要一次 （true）.eslintrc-auto-import.json
      }),
      Components({
        // 解析组建
        resolvers: [ElementPlusResolver()]
        // 所有的组建可以自动加载
        // dirs: ['src/components', 'src/layout']
      }),
      ElementPlus({}),
      visualizer({
        open: false
      }),
      // 图片压缩
      viteImagemin({
        gifsicle: {
          optimizationLevel: 7,
          interlaced: false
        },
        optipng: {
          optimizationLevel: 7
        },
        mozjpeg: {
          quality: 20
        },
        pngquant: {
          quality: [0.8, 0.9],
          speed: 4
        },
        svgo: {
          plugins: [
            {
              name: 'removeViewBox'
            },
            {
              name: 'removeEmptyAttrs',
              active: false
            }
          ]
        }
      })
    ]
  }
})
